package com.codeoss.framework.controller;

import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.codeoss.framework.response.AttachmentResponse;
import com.codeoss.framework.service.IAttachmentService;
import com.codeoss.framework.util.IOUtil;

@Controller
@RequestMapping("attachment")
public class AttachmentController {
	@Autowired
	private IAttachmentService attachmentService;
	
	@RequestMapping(value = "init", method = RequestMethod.GET)
	@ResponseBody
	public AttachmentResponse init(@RequestParam("model") String model,@RequestParam("recordId") Long recordId){
		AttachmentResponse attachmentResponse=attachmentService.init(model, recordId);
		return attachmentResponse;
	}
	
	@RequestMapping(value = "upload", method = RequestMethod.POST)
	@ResponseBody
	public AttachmentResponse upload(@RequestParam("model") String model,@RequestParam("recordId") Long recordId,@RequestParam("file") MultipartFile file){
		AttachmentResponse attachmentResponse=attachmentService.upload(model, recordId,file);
		return attachmentResponse;
	}
	
	@RequestMapping(value = "download", method = RequestMethod.GET)
	public void download(@RequestParam("id") Long id, HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse)throws Exception {
		AttachmentResponse attachmentResponse=attachmentService.download(id);
		httpServletResponse.reset();
		try {
			httpServletResponse.addHeader("Content-Disposition","attachment;filename="+new String(attachmentResponse.getOriginalFilename().getBytes(),"ISO-8859-1"));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		OutputStream out=httpServletResponse.getOutputStream();
		InputStream is=null;
		try {
			is=attachmentResponse.getInputStream();
			byte[] b=new byte[1024];
			int len;
			while((len=is.read(b))!=-1) {
				out.write(b, 0, len);
			}
		}catch(Exception e) {
			throw e;
		}finally {
			IOUtil.closeInputStream(is);
		}
	}
	
	@RequestMapping(value = "deleteAttachment", method = RequestMethod.POST)
	@ResponseBody
	public AttachmentResponse deleteAttachment(@RequestParam("id") Long id){
		AttachmentResponse attachmentResponse=attachmentService.deleteAttachment(id);
		return attachmentResponse;
	}
}
